package pannel.product;

import pannel.order.Order;
import pannel.order.OrderDao;
import pannel.user.User;
import pannel.cart.Cart;
import pannel.cart.CartDao;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.sql.SQLException;
import java.util.Date;

public class ProductCard extends JPanel {
    private Product product;
    private JLabel imageLabel;
    private JLabel nameLabel;
    private JLabel priceLabel;
    private JLabel stockLabel;

    public ProductCard(Product product) {
        this.product = product;
        setupUI();
    }

    private void setupUI() {
        setLayout(new BorderLayout(10, 10));
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200), 1, true));
        setPreferredSize(new Dimension(200, 280));

        // 图片面板
        imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(JLabel.CENTER);
        imageLabel.setPreferredSize(new Dimension(180, 180));
        updateImage();

        // 信息面板
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setBackground(Color.WHITE);
        infoPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10));

        nameLabel = new JLabel(product.getName());
        nameLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        
        priceLabel = new JLabel(String.format("￥%.2f", product.getPrice()));
        priceLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        priceLabel.setForeground(new Color(255, 68, 68));
        
        stockLabel = new JLabel("库存: " + product.getStock());
        stockLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        stockLabel.setForeground(Color.GRAY);

        infoPanel.add(nameLabel);
        infoPanel.add(Box.createVerticalStrut(5));
        infoPanel.add(priceLabel);
        infoPanel.add(Box.createVerticalStrut(5));
        infoPanel.add(stockLabel);

        add(imageLabel, BorderLayout.CENTER);
        add(infoPanel, BorderLayout.SOUTH);

        // 添加鼠标悬停效果
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                setBackground(new Color(245, 245, 245));
                infoPanel.setBackground(new Color(245, 245, 245));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                setBackground(Color.WHITE);
                infoPanel.setBackground(Color.WHITE);
            }

            public void mouseClicked(java.awt.event.MouseEvent evt) {
                showOrderDialog();
            }
        });
    }

    private void updateImage() {
        try {
            ImageIcon originalIcon = new ImageIcon(product.getImagePath());
            Image image = originalIcon.getImage();
            Image scaledImage = image.getScaledInstance(160, 160, Image.SCALE_SMOOTH);
            imageLabel.setIcon(new ImageIcon(scaledImage));
        } catch (Exception e) {
            // 使用默认图片
            imageLabel.setIcon(createDefaultIcon());
        }
    }

    private ImageIcon createDefaultIcon() {
        BufferedImage defaultImage = new BufferedImage(160, 160, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = defaultImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(new Color(240, 240, 240));
        g2d.fillRect(0, 0, 160, 160);
        g2d.setColor(Color.GRAY);
        g2d.drawRect(0, 0, 159, 159);
        g2d.dispose();
        return new ImageIcon(defaultImage);
    }

    private void showOrderDialog() {
        String quantityStr = JOptionPane.showInputDialog(
            this,
            "请输入数量:",
            "加入购物车",
            JOptionPane.PLAIN_MESSAGE
        );
        
        if (quantityStr != null && !quantityStr.trim().isEmpty()) {
            try {
                int quantity = Integer.parseInt(quantityStr);
                if (quantity <= 0) {
                    JOptionPane.showMessageDialog(this, "请输入有效的数量");
                    return;
                }
                if (quantity > product.getStock()) {
                    JOptionPane.showMessageDialog(this, "库存不足");
                    return;
                }
                
                CartDao cartDao = new CartDao();
                // 检查商品是否已在购物车
                Cart existCart = cartDao.checkExist(getCurrentUser().getId(), product.getId());
                
                if (existCart != null) {
                    // 更新数量
                    int newQuantity = existCart.getQuantity() + quantity;
                    if (newQuantity > product.getStock()) {
                        JOptionPane.showMessageDialog(this, "库存不足");
                        return;
                    }
                    if (cartDao.updateQuantity(existCart.getId(), newQuantity)) {
                        JOptionPane.showMessageDialog(this, "已更新购物车数量");
                    }
                } else {
                    // 添加到购物车
                    Cart cart = Cart.builder()
                            .userId(getCurrentUser().getId())
                            .productId(product.getId())
                            .quantity(quantity)
                            .build();
                            
                    if (cartDao.add(cart)) {
                        JOptionPane.showMessageDialog(this, "已加入购物车");
                    } else {
                        JOptionPane.showMessageDialog(this, "加入购物车失败");
                    }
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字");
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "操作失败：" + e.getMessage());
            }
        }
    }

    private User getCurrentUser() {
        Container c = getParent();
        while (c != null && !(c instanceof ProductListPage)) {
            c = c.getParent();
        }
        if (c instanceof ProductListPage) {
            return ((ProductListPage) c).getCurrentUser();
        }
        return null;
    }
} 